package com.lz.sports.vm

import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import androidx.room.RoomDatabase
import com.lz.comm.viewmodel.DataModel
import com.lz.library.base.BaseViewModel
import com.lz.library.extension.isRecyclerViewScrolledLast
import com.lz.sports.bean.PageList

abstract class ListViewModel<T>(model: DataModel = DataModel()) : BaseViewModel<DataModel>(model) {

    companion object {
        const val DEF_LIMIT = 10
    }
    //当前页, 从0开始
    protected var page = 0
    //分页数量
    protected var limit = DEF_LIMIT
    //正在加载
    protected var isLoading = false

    val pageListData = MutableLiveData<PageList<T>>()

    protected inline fun <reified T> getService(): T = model!!.getService(T::class.java)

    protected inline fun <reified T : RoomDatabase> getRoomDatabase(dbName: String): T =
        model!!.getRoomDatabase(T::class.java, dbName)

    fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
        if (isLoading) return
        if (hasNext() && isRecyclerViewScrollLast(rv)) {
            pagingNext()
        }
    }

    //分页递增
    fun pageAdd() {
        page += limit
    }

    protected fun hasNext(): Boolean = pageListData.value?.hasNext == true

    //翻页
    protected abstract fun pagingNext()

    /**
     * recyclerview是否滑动到最底下,根据实际情况来
     * 在有添加Footer与没有添加时的最后一项位置
     * @param rv
     * @return
     */
    protected open fun isRecyclerViewScrollLast(rv: RecyclerView): Boolean = rv.isRecyclerViewScrolledLast()

}